package com.gupt.youhd.controller;/*
@author name
@data 2023/4/19-23:45
*/

import com.gupt.youhd.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {  //文件上传下载的工具controller

    @Value("${youHD.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){  //file属性名于前端name=xxx保持一致
        //此处的file是一个临时文件，需存储，不然会消失
        log.info(file.toString());

        //获取源文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID覆盖文件名（保持不重复  suffix:后缀
        String fileName = UUID.randomUUID().toString() + suffix;

        //判断当前目录有无 无：则新建
        File dir = new File(basePath);
        if(!dir.exists()){
            dir.mkdir();
        }

        try {
            //将临时文件转化为新目录下
            file.transferTo(new File(basePath+fileName));  //配置的目录+uuid的文件名
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流：读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
            //输出流：将文件写到浏览器，
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");   //设置响应类型

            //读取文件内容：用byte存储
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){    //-1:表示读完
                outputStream.write(bytes,0,len);  //第0个写len长度
                outputStream.flush();  //刷新
            }
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
